let configuration = require('../../configuration');

class Background {
    constructor() {
        this.width = configuration.get('window.width');
        this.height = configuration.get('window.height');
        configuration.getImage('background', image => {
            this.background = image;
        });
    }

    draw(canvas) {
        if (!this.background) return;
        let image = this.background;
        if (image.width / image.height != this.width / this.height) {
            // cut
            // image.width -> iW, image.height -> iH
            // this.width -> tW, this.height -> tH
            // assume (iW - a) / iH = tW / tH
            // iW / iH - a / iH = tW / tH
            // a / iH = iW / iH - tW / tH
            // a = iW - tW * iH / tH
            // a > 0 => iW > tW * iH / tH => iW * tH > tW * iH
            let a = image.width - this.width * image.height / this.height;

            // assume iW / (iH - b) = tW / tH
            // tW * (iH - b) = iW * tH
            // tW * b = tW * iH - iW * tH
            // b = iH - iW * tH / tW
            // b > 0 => iH > iW * tH / tW => iH * tW > iW * tH
            let b = image.height - image.width * this.height / this.width;

            if (b > 0) {
                // cut height
                canvas.getContext('2d').drawImage(image, 0, 0, image.width, image.height - b, 0, 0, this.width, this.height);
            } else {
                // cut width
                canvas.getContext('2d').drawImage(image, 0, 0, image.width - a, image.height, 0, 0, this.width, this.height);
            }
        } else {
            canvas.getContext('2d').drawImage(image, 0, 0, this.width, this.height);
        }
    }
}

module.exports = Background;
